package com.xgpro.common.websocket;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName CustomHandler
 * @Author: LiKai
 * @Date: 2019-09-07 11:35
 * @Version 1.0
 * @Description 实现WebSocket建立接连、发送消息、断开连接等的处理类
 */

@Component
public class CustomHandler extends TextWebSocketHandler {

    private static final Logger logger = LoggerFactory.getLogger(CustomHandler.class);

    //存储用户连接webSocket信息
    private static final Map<String, WebSocketSession> users;
    //用户标识
    private static final String CLIENT_ID = "username";

    static {
        users = new HashMap<String, WebSocketSession>();
    }

    //建立连接后的操作
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.info("=========================>成功建立连接");
        String username = getClientId(session);
        //  logger.info("=========================>userId:"+username);
        if (username != null) {
            users.put(username, session);
            Map<String,Boolean> map = new HashMap<>();
            map.put("success",true);
            String jsonString = JSON.toJSONString(map);
            session.sendMessage(new TextMessage(jsonString));

        }
    }

    //消息处理，在客户端通过 webSocket API 发送的消息会经过这里，然后进行相应的处理
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        logger.info("=========================>"+message.getPayload());
        WebSocketMessage message1 = new TextMessage("server:" + message);
        try {
            session.sendMessage(message1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送信息给指定用户
     *
     * @param clientId
     * @param message
     * @return
     */
    public boolean sendMessageToUser(String clientId, TextMessage message) {
        if (users.get(clientId) == null) {
            logger.info("=========================>当前用户未连接");
            return false;
        }
        WebSocketSession session = users.get(clientId);
        logger.info("=========================>sendMessage:" + session);
        if (!session.isOpen()) {
            logger.info("=========================>连接未打开");
            return false;
        }
        try {
            session.sendMessage(message);
            logger.info("=========================>消息内容："+message);
        } catch (IOException e) {
            logger.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 广播信息，发送消息给所有的在线用户
     *
     * @param message
     * @return
     */
    public boolean sendMessageToAllUsers(TextMessage message) {
        boolean allSendSuccess = true;
        Set<String> clientIds = users.keySet();
        WebSocketSession session = null;
        for (String clientId : clientIds) {
            try {
                session = users.get(clientId);
                if (session.isOpen()) {
                    session.sendMessage(message);
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
                allSendSuccess = false;
            }
        }

        return allSendSuccess;
    }


    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        logger.error("=========================>连接出错：");
        users.remove(getClientId(session));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        logger.error("=========================>连接已关闭：");
        users.remove(getClientId(session));
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 获取用户标识
     *
     * @param session
     * @return
     */
    private String getClientId(WebSocketSession session) {
        try {
            Integer clientId = (int)session.getAttributes().get(CLIENT_ID);
            return clientId+"";
        } catch (Exception e) {
            return null;
        }
    }
}
